﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace EmptoolWebApp.Controllers
{
    public class DemoController : Controller
    {
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(DemoController));

        // GET: Demo
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult ClaimDemo()
        {
            EmptoolWebApp.Models.DemoViewModel vm = new Models.DemoViewModel();
            vm.ClaimList = System.Security.Claims.ClaimsPrincipal.Current.Claims;

            return View(vm);
        }

        public ActionResult FileDemo()
        {
            // Reference
            // https://azure.microsoft.com/en-us/documentation/articles/storage-dotnet-how-to-use-files/
            return View();
        }

        public ActionResult BlobDemo()
        {
            return View();
        }

        public class CustomerEntity : Microsoft.WindowsAzure.Storage.Table.TableEntity
        {
            public CustomerEntity(string lastName, string firstName)
            {
                this.PartitionKey = lastName;
                this.RowKey = firstName;
            }

            public CustomerEntity() { }

            public string Email { get; set; }

            public string PhoneNumber { get; set; }
        }

        public ActionResult TableDemo()
        {
            //Microsoft.Azure.CloudConfigurationManager
            Microsoft.WindowsAzure.Storage.CloudStorageAccount storageAccount =
                Microsoft.WindowsAzure.Storage.CloudStorageAccount.Parse(
                    Microsoft.Azure.CloudConfigurationManager.GetSetting("StorageConnectionString"));

            Microsoft.WindowsAzure.Storage.Table.CloudTableClient tableClient = storageAccount.CreateCloudTableClient();

            // Retrieve a reference to the table.
            Microsoft.WindowsAzure.Storage.Table.CloudTable table = tableClient.GetTableReference("people");

            // Create the table if it doesn't exist.
            table.CreateIfNotExists();


            // Create a new customer entity.
            CustomerEntity customer1 = new CustomerEntity("Harp", "Walter");
            customer1.Email = "Walter@contoso.com";
            customer1.PhoneNumber = "425-555-0101";

            // Create the TableOperation object that inserts the customer entity.
            Microsoft.WindowsAzure.Storage.Table.TableOperation insertOperation = Microsoft.WindowsAzure.Storage.Table.TableOperation.Insert(customer1);

            // Execute the insert operation.
            table.Execute(insertOperation);

            // Reference 
            // https://azure.microsoft.com/en-us/documentation/articles/storage-dotnet-how-to-use-tables/#set-up-your-development-environment

            return View();
        }

        public ActionResult QueueDemo()
        {
            return View();
        }

        public ActionResult EmailDemo()
        {
            string senderEmailAddress = "zhixian@hotmail.com";
            string recipientEmailAddress = "zhixian@aporigin.com";
            string emailBody = "This is a testing email message";

            System.Net.Mail.MailMessage emailMessage = new System.Net.Mail.MailMessage(
                senderEmailAddress,
                recipientEmailAddress,
                "Email Test",
                emailBody);

            emailMessage.Bcc.Add(new System.Net.Mail.MailAddress("zhixian@aporigin.com"));
            emailMessage.SubjectEncoding = System.Text.Encoding.UTF8;
            emailMessage.BodyEncoding = System.Text.Encoding.UTF8;
            emailMessage.IsBodyHtml = true;

            System.Net.Mail.SmtpClient s = new System.Net.Mail.SmtpClient();

            try
            {
                s.Send(emailMessage);
            }
            catch (Exception)
            {

            }

            return View();
        }

        public ActionResult ErrorEmailDemo()
        {
            log.Error("Sample ErrorEmail");

            log4net.ILog log2 = log4net.LogManager.GetLogger("EmpToolWebsiteLog");

            log2.Error("Sample ErrorEmail 2222");

            throw new Exception("Sample ErrorEmail");

            //return View();
        }

        // GET: Demo/Details/5
        public ActionResult Details(int id)
        {
            return View();
        }

        // GET: Demo/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: Demo/Create
        [HttpPost]
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                // TODO: Add insert logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        // GET: Demo/Edit/5
        public ActionResult Edit(int id)
        {
            return View();
        }

        // POST: Demo/Edit/5
        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add update logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        // GET: Demo/Delete/5
        public ActionResult Delete(int id)
        {
            return View();
        }

        // POST: Demo/Delete/5
        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add delete logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        public ActionResult InitDemo()
        {
            DateTime now = DateTime.UtcNow;

            //public string Owner { get; set; }
            //public string Creator { get; set; }
            //public DateTime? CreationDateTime { get; set; }
            //public string Revisor { get; set; }
            //public DateTime? RevisionDateTime { get; set; }

            //public string Email { get; set; }
            //public string PasswordHash { get; set; }
            //public string PasswordSalt { get; set; }
            //public DateTime? PasswordExpiryDateTime { get; set; }

            Entities.UserAccountEntity account = new Entities.UserAccountEntity("zhixian@hotmail.com")
            {
                //Owner = "SYSTEM",
                //Creator = "SYSTEM",
                //CreationDateTime = now,
                //Revisor = "SYSTEM",
                //RevisionDateTime = now,
                Email = "zhixian@hotmail.com",
                PasswordHash = "P@ssw0rd",
                PasswordSalt = new Guid().ToString()
                //,PasswordExpiryDateTime = now

            };
            Microsoft.WindowsAzure.Storage.Table.TableOperation insertOperation = Microsoft.WindowsAzure.Storage.Table.TableOperation.Insert(account);

            try
            {
                Microsoft.WindowsAzure.Storage.Table.CloudTable tbl = Helpers.AzureStorageHelper.GetStorageTable(Entities.UserAccountEntity.TABLE_NAME);
                tbl.Execute(insertOperation);

                //Helpers.AzureStorageHelper.GetStorageTable(Entities.UserAccountEntity.TABLE_NAME).Execute(insertOperation);
            }
            catch (Exception)
            {
                throw;
            }

            return View();
        }

        public ActionResult CastTest()
        {
            Models.AzureStorageUserStore store = new Models.AzureStorageUserStore();

            Microsoft.AspNet.Identity.IUserStore<Models.ApplicationUser> a = store as Microsoft.AspNet.Identity.IUserStore<Models.ApplicationUser>;

            return View();
        }

        public void RemovedCallback(String k, Object v, System.Web.Caching.CacheItemRemovedReason r)
        {
            //itemRemoved = true;
            //reason = r;
            // Add item back into cache
        }

        public void CacheItemRemovedCallback(System.Runtime.Caching.CacheEntryRemovedArguments args)
        {
        }

        public ActionResult CacheTest()
        {
            System.Web.Caching.Cache c = new System.Web.Caching.Cache();
            Dictionary<string, object> objToCache = new Dictionary<string, object>();
            DateTime expirationDateTime = new DateTime().AddSeconds(10);
            c.Insert("TestCache", objToCache, null, expirationDateTime, System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Default, RemovedCallback);

            
            System.Runtime.Caching.MemoryCache mc = new System.Runtime.Caching.MemoryCache("AAA", null);
            System.Runtime.Caching.CacheItem ci = new System.Runtime.Caching.CacheItem("TEST_CACHE_ITEM", objToCache);
            System.Runtime.Caching.CacheItemPolicy cip = new System.Runtime.Caching.CacheItemPolicy();
            cip.AbsoluteExpiration = new DateTimeOffset(DateTime.Now, new TimeSpan(0, 0, 15));
            cip.SlidingExpiration = System.Runtime.Caching.MemoryCache.NoSlidingExpiration;
            cip.RemovedCallback = CacheItemRemovedCallback;
            cip.Priority = System.Runtime.Caching.CacheItemPriority.Default;

            

            mc.AddOrGetExisting(ci, cip);

            return View();
        }

        public ActionResult AssessmentTest()
        {
            return View();
        }

        public ActionResult VideoUploadTest()
        {
            return View();
        }

        public ActionResult ButtonPlaceHolderTest()
        {
            return View();
        }

        public ActionResult TabulationTest()
        {
            return View();
        }

        public ActionResult VerticalCentreTest()
        {
            return View();
        }

        public ActionResult CropboxTest()
        {
            return View();
        }

        public ActionResult ResultTest()
        {
            return View();
        }

        ////////////////////////////////////////
        // Retrieve all records (Generic)
        //Microsoft.WindowsAzure.Storage.Table.TableQuery tq = new Microsoft.WindowsAzure.Storage.Table.TableQuery();
        //List<Microsoft.WindowsAzure.Storage.Table.DynamicTableEntity> list = tbl.ExecuteQuery(tq).ToList();

        ////////////////////////////////////////
        // Using ExecuteQuerySegmented method
        //Microsoft.WindowsAzure.Storage.Table.TableContinuationToken token = null;
        //var entities = new List<Microsoft.WindowsAzure.Storage.Table.DynamicTableEntity>();
        //do
        //{
        //    var queryResult = tbl.ExecuteQuerySegmented(new tq(), token);
        //    entities.AddRange(queryResult.Results);
        //    token = queryResult.ContinuationToken;
        //} while (token != null);

    }
}
